import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  Card,
  Table,
  Button,
  Space,
  Badge,
  Progress,
  Typography,
  Tag,
  Message,
} from '@arco-design/web-react'
import { IconEye, IconStop, IconRefresh } from '@arco-design/web-react/icon'
import { getRunningInstances, cancelTask } from '@/api/task'
import type { PipelineInstance } from '@/types'
import dayjs from 'dayjs'
import './index.css'

const { Title, Text } = Typography

// 状态映射
const statusMap: Record<number, { text: string; color: string; status: any }> = {
  0: { text: '等待中', color: 'gray', status: 'default' },
  1: { text: '运行中', color: 'blue', status: 'processing' },
  2: { text: '成功', color: 'green', status: 'success' },
  3: { text: '失败', color: 'red', status: 'error' },
  4: { text: '已取消', color: 'orange', status: 'warning' },
}

export default function TaskPage() {
  const navigate = useNavigate()
  const [loading, setLoading] = useState(false)
  const [instances, setInstances] = useState<PipelineInstance[]>([])

  // 加载运行中的实例
  const loadInstances = async () => {
    setLoading(true)
    try {
      const data = await getRunningInstances()
      setInstances(data)
    } catch (error) {
      console.error('Failed to load instances:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadInstances()

    // 每 5 秒自动刷新
    const timer = setInterval(loadInstances, 5000)
    return () => clearInterval(timer)
  }, [])

  // 取消实例
  const handleCancel = async (instanceId: number) => {
    try {
      await cancelTask(instanceId)
      Message.success('已取消任务')
      loadInstances()
    } catch (error) {
      console.error('Failed to cancel task:', error)
    }
  }

  const columns = [
    {
        title: '流水线',
        dataIndex: 'pipeline.name',
        key: 'pipelineName',
        render: (name: string) => <strong>{name || '-'}</strong>,
      },
    {
      title: '提交信息',
      dataIndex: 'commitMessage',
      key: 'commitMessage',
      render: (message: string) => (
        <Text ellipsis={{ showTooltip: true }} style={{ maxWidth: 300 }}>
          {message}
        </Text>
      ),
    },
    {
      title: '提交哈希',
      dataIndex: 'commitHash',
      key: 'commitHash',
      width: 120,
      render: (hash: string) => (
        <Tag style={{ fontFamily: 'monospace' }}>
          {hash?.substring(0, 8)}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: number) => {
        const config = statusMap[status] || statusMap[0]
        return <Badge status={config.status} text={config.text} />
      },
    },
    {
      title: '进度',
      key: 'progress',
      width: 150,
      render: (_: any, record: PipelineInstance) => {
        // 简单的进度计算：如果是运行中，显示不确定进度，否则显示100%或0%
        const progress =
          record.status === 1 ? undefined : record.status === 2 ? 100 : 0
        return (
          <Progress
            percent={progress || 0}
            status={
              record.status === 2
                ? 'success'
                : record.status === 3
                ? 'error'
                : undefined
            }
          />
        )
      },
    },
    {
      title: '触发人',
      dataIndex: 'triggeredBy',
      key: 'triggeredBy',
      width: 120,
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 180,
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_: any, record: PipelineInstance) => (
        <Space>
          <Button
            type="text"
            size="small"
            icon={<IconEye />}
            onClick={() => navigate(`/task/instance/${record.id}`)}
          >
            详情
          </Button>
          {record.status === 1 && (
            <Button
              type="text"
              size="small"
              status="danger"
              icon={<IconStop />}
              onClick={() => handleCancel(record.id)}
            >
              取消
            </Button>
          )}
        </Space>
      ),
    },
  ]

  return (
    <div className="task-page">
      <div className="task-header">
        <Title heading={4}>任务监控</Title>
        <Button
          type="primary"
          icon={<IconRefresh />}
          onClick={loadInstances}
          loading={loading}
        >
          刷新
        </Button>
      </div>

      <Card>
        <Table
          columns={columns}
          data={instances}
          loading={loading}
          pagination={false}
          rowKey="id"
          noDataElement={
            <div style={{ textAlign: 'center', padding: '40px 0' }}>
              <Text type="secondary">暂无运行中的任务</Text>
            </div>
          }
        />
      </Card>
    </div>
  )
}
